package org.jsola.hr.web;

import org.jsola.admin.vo.HeaderFieldsListVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.CompanyNecessaryFieldAddDTO;
import org.jsola.hr.dto.CompanyNecessaryFieldBatchDTO;
import org.jsola.hr.dto.CompanyNecessaryFieldUpdateDTO;
import org.jsola.hr.dto.UpdateEmpFieldDTO;
import org.jsola.hr.query.CompanyNecessaryFieldQuery;
import org.jsola.hr.query.ModuleFieldQuery;
import org.jsola.hr.service.ICompanyNecessaryFieldService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.async.IAsyncEmpInfoDetailService;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 公司员工必填字段信息
 *
 * @author zhr
 */
@RestController("hrCompanyNecessaryFieldController")
@RequestMapping(HrConstants.API_PATH + "/v1/companyNecessaryFields")
public class CompanyNecessaryFieldController implements ICompanyNecessaryFieldControllerAPI {

    @Autowired
    private ICompanyNecessaryFieldService companyNecessaryFieldService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private IAsyncEmpInfoDetailService asyncEmpInfoDetailService;

    @Override
    @GetMapping("/getCustomField/{companyId}")
    public Result<List<HeaderFieldsListVO>> getCustomField(@PathVariable String companyId) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                companyNecessaryFieldService.getCustomField(companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/addFiledForAllCompany")
    public Result<Integer> addFiledForAllCompany(@Valid @RequestBody CompanyNecessaryFieldAddDTO companyNecessaryFieldAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.addFiledForAllCompany(companyNecessaryFieldAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping
    public Result<CompanyNecessaryFieldVO> save(@Valid @RequestBody CompanyNecessaryFieldAddDTO companyNecessaryFieldAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.save(companyNecessaryFieldAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody CompanyNecessaryFieldUpdateDTO companyNecessaryFieldUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        int count = companyNecessaryFieldService.update(companyNecessaryFieldUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }

        //更新员工的 “信息补充 未完善、已完善”
        List<String> list = empInfoService.listEmpIdByCompany(companyNecessaryFieldUpdateDTO.getCompanyId(), tokenUser.getSiteId());
        asyncEmpInfoDetailService.empCompleteInfoAsync(list, tokenUser);

        return Result.success(count);
    }

    @Override
    @PutMapping(value = "/updateForApp")
    public Result<Integer> updateForApp(@Valid @RequestBody CompanyFieldAndValueListVO companyFieldAndValueListVO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        int count = companyNecessaryFieldService.updateForApp(companyFieldAndValueListVO, tokenUser, companyFieldAndValueListVO.getType());
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping(value = "/updateAppForModule")
    public Result<Integer> updateAppForModule(@Valid @RequestBody CompanyFieldAndValueUpdateVO companyFieldAndValueUpdateVO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        int count = companyNecessaryFieldService.updateAppForModule(companyFieldAndValueUpdateVO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody CompanyNecessaryFieldBatchDTO companyNecessaryFieldBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<CompanyNecessaryFieldAddDTO> companyNecessaryFieldAddDTOList = companyNecessaryFieldBatchDTO.getCompanyNecessaryFieldAddDTOList();
        if (!CollectionUtils.isEmpty(companyNecessaryFieldAddDTOList)) {
            companyNecessaryFieldService.batchSave(companyNecessaryFieldAddDTOList,tokenUser);
        }
        // 修改
        List<CompanyNecessaryFieldUpdateDTO> companyNecessaryFieldUpdateDTOList = companyNecessaryFieldBatchDTO.getCompanyNecessaryFieldUpdateDTOList();
        if (!CollectionUtils.isEmpty(companyNecessaryFieldUpdateDTOList)) {
            companyNecessaryFieldUpdateDTOList.parallelStream().forEach(
                    companyNecessaryFieldUpdateDTO -> {
                        companyNecessaryFieldService.update(companyNecessaryFieldUpdateDTO,tokenUser);
                    }
            );
        }
        // 删除
        List<String> deleteCompanyNecessaryFieldIdList = companyNecessaryFieldBatchDTO.getDeleteCompanyNecessaryFieldIdList();
        if (!CollectionUtils.isEmpty(deleteCompanyNecessaryFieldIdList)) {
            companyNecessaryFieldService.deleteByIds(tokenUser,deleteCompanyNecessaryFieldIdList.toArray(new String[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{companyNecessaryFieldId}")
    public Result<Integer> delete(@PathVariable String companyNecessaryFieldId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除公司员工必填字段信息权限校验

        int count = companyNecessaryFieldService.deleteByIds(tokenUser, companyNecessaryFieldId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] companyNecessaryFieldIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除公司员工必填字段信息权限校验

        int count = companyNecessaryFieldService.deleteByIds(tokenUser, companyNecessaryFieldIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{companyNecessaryFieldId}")
    public Result<CompanyNecessaryFieldVO> findById(@PathVariable String companyNecessaryFieldId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.selectById(companyNecessaryFieldId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<CompanyNecessaryFieldListVO>> listAll(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.select(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listAllForPc")
    public Result<CompanyFieldForPcListVO> listAllForPc(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.listAllForPc(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listForPc")
    public Result<List<CompanyFieldInfoVO>> listForPc(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        ParamException.notNull(companyNecessaryFieldQuery.getCompanyId(), "请选择公司");
        return Result.success(
                companyNecessaryFieldService.listForPc(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listForPc2")
    public Result<List<CompanyFieldInfoVO>> listForPc2(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        
        ParamException.notNull(companyNecessaryFieldQuery.getCompanyId(), "请选择公司");
        return Result.success(
                companyNecessaryFieldService.listForPc2(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listCompanyModuleCodes")
    public Result<List<CompanyNecessaryModuleCodeVO>> listCompanyModuleCodes(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        ParamException.notNull(companyNecessaryFieldQuery.getCompanyId(), "请选择公司");
        ParamException.notNull(companyNecessaryFieldQuery.getEmpInfoId(), "未查询到员工信息");
        return Result.success(companyNecessaryFieldService.listCompanyModuleCodes(companyNecessaryFieldQuery, tokenUser));
    }

    @Override
    @GetMapping(value = "/listCompanyModuleCodesForEmployee")
    public Result<List<CompanyNecessaryModuleCodeVO>> listCompanyModuleCodesForEmployee(CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        ParamException.notNull(companyNecessaryFieldQuery.getCompanyId(), "请选择公司");
        ParamException.notNull(companyNecessaryFieldQuery.getEmpInfoId(), "未查询到员工信息");
        return Result.success(companyNecessaryFieldService.listCompanyModuleCodesForEmployee(companyNecessaryFieldQuery, tokenUser));
    }

    @Override
    @GetMapping(value = "/getEmpFieldValue")
    public Result<EmpFieldValueVO> getEmpFieldValue(@Valid ModuleFieldQuery moduleFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        ParamException.notNull(moduleFieldQuery.getCompanyId(), "请选择公司");
        ParamException.notNull(moduleFieldQuery.getEmpInfoId(), "未查询到员工信息");
        return Result.success(companyNecessaryFieldService.getEmpFieldValue(moduleFieldQuery, tokenUser));
    }

    @Override
    @GetMapping(value = "/getAllEmpFieldValue")
    public Result<Map<String,EmpFieldValueVO>> getAllEmpFieldValue(@Valid ModuleFieldQuery moduleFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        ParamException.notNull(moduleFieldQuery.getCompanyId(), "请选择公司");
        ParamException.notNull(moduleFieldQuery.getEmpInfoId(), "未查询到员工信息");
        return Result.success(companyNecessaryFieldService.getAllEmpFieldValue(moduleFieldQuery, tokenUser));
    }

    @Override
    @PostMapping("/empFieldValue")
    public Result<String> saveEmpFieldValue(@RequestBody @Valid UpdateEmpFieldDTO updateEmpFieldDTO,
                                            @RequestParam(value = "isVerify", required = false) Boolean isVerify) {
        TokenUser tokenUser = UserContext.getUser();

        //判断身份证号是否在同租户下已存在
        Map<String,String> map = updateEmpFieldDTO.getData();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry maps = ( Map.Entry)iterator.next();
            Object key = maps.getKey();
            if (key.equals("idCard")) {
                String value = (String) maps.getValue();
                Map<String,Object> isExitMap = empInfoService.isExit(tokenUser.getSiteId() ,updateEmpFieldDTO.getEmpInfoId(), value);
                if ((boolean)isExitMap.get("flag")) {
                    String msg = "身份证号已在用工单位:["+ (String) isExitMap.get("msg") +"]存在";
                    throw new ParamException(msg);
                }
            }
        }
        companyNecessaryFieldService.updateEmpFieldValue(updateEmpFieldDTO, HttpMethod.POST, true, tokenUser);

        //更新员工的 “信息补充 未完善、已完善”
        List<String> list = new ArrayList<>();
        list.add(updateEmpFieldDTO.getEmpInfoId());
        empInfoService.empCompleteInfo(list, tokenUser);
        return Result.success();
    }

    @Override
    @PutMapping("/empFieldValue")
    public Result<String> updateEmpFieldValue(@RequestBody @Valid UpdateEmpFieldDTO updateEmpFieldDTO) {
        TokenUser tokenUser = UserContext.getUser();
        companyNecessaryFieldService.updateEmpFieldValue(updateEmpFieldDTO, HttpMethod.PUT, true, tokenUser);

        //更新员工的 “信息补充 未完善、已完善”
        List<String> list = new ArrayList<>();
        list.add(updateEmpFieldDTO.getEmpInfoId());
        empInfoService.empCompleteInfo(list, tokenUser);
        return Result.success();
    }

    @Override
    @DeleteMapping("/empFieldValue")
    public Result<String> deleteEmpFieldValue(@RequestBody @Valid UpdateEmpFieldDTO updateEmpFieldDTO) {
        TokenUser tokenUser = UserContext.getUser();
        companyNecessaryFieldService.updateEmpFieldValue(updateEmpFieldDTO, HttpMethod.DELETE, false, tokenUser);

        //更新员工的 “信息补充 未完善、已完善”
        List<String> list = new ArrayList<>();
        list.add(updateEmpFieldDTO.getEmpInfoId());
        empInfoService.empCompleteInfo(list, tokenUser);
        return Result.success();
    }

    @Override
    @GetMapping("/checkEmpFieldValue")
    public Result<String> checkEmpFieldValue(String empInfoId, String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        companyNecessaryFieldService.checkEmpFieldValue(empInfoId, companyId, tokenUser);
        return Result.success();
    }

    @Override
    @GetMapping(value = "/listAllForApp")
    public Result<CompanyFieldAndValueListVO> listAllForApp(CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.listAllForApp(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listNecessaryModeForApp")
    public Result<List<String>> listNecessaryModeForApp(CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.listNecessaryModeForApp(companyNecessaryFieldQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listForAppModule")
    public Result<List<CompanyNecessaryFieldVO>> listForAppModule(CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.listForAppModule(companyNecessaryFieldQuery, tokenUser)
        );
    }


    @Override
    @GetMapping
    public Result<Page<CompanyNecessaryFieldListVO>> page(@Valid CompanyNecessaryFieldQuery companyNecessaryFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                companyNecessaryFieldService.selectPage(companyNecessaryFieldQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/updateNecessaryBatch")
    public Result<Integer> updateNecessaryBatch(@Valid @RequestBody CompanyNecessaryFieldBatchDTO companyNecessaryFieldBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.updateNecessaryBatch(companyNecessaryFieldBatchDTO, tokenUser)
        );
    }

    @PostMapping("/initSystemData")
    public Result<Integer> initSystemData() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.initSystemData(tokenUser)
        );
    }

    @PutMapping("/updateBySystemData")
    public Result<Integer> updateBySystemData() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.updateBySystemData()
        );
    }

    @PostMapping("/addAllCompanyFields/{yourName}")
    public Result<Integer> addAllCompanyFields(@PathVariable String yourName
            , @RequestBody List<CompanyNecessaryFieldAddDTO> companyNecessaryFieldAddDTOList) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改公司员工必填字段信息权限校验

        return Result.success(
                companyNecessaryFieldService.addAllCompanyFields(yourName, companyNecessaryFieldAddDTOList)
        );
    }

}

